<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div class="upload_elements">
    <div class="steps">
      <el-steps :active="active" style="width: 100%" align-center>
        <el-step title="文件上传" />
        <el-step title="压缩包文件解析" />
        <el-step title="完成" />
      </el-steps>
    </div>
    <div class="upload" v-show="active === 1" v-loading="uploadLoading" element-loading-text="压缩包解压中...">
      <div class="upload_content">
        <el-form size="small" label-width="120">
          <el-form-item label="机型：" required>
            <el-select style="width: 400px" v-model="uploadForm.structureModelId" clearable placeholder="请选择机型">
              <el-option v-for="item in structureModel" :label="item.name" :value="item.name" :key="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="索引文件名：" >
            <el-input style="width: 400px" v-model="uploadForm.indexFileName" placeholder="请输入索引文件名，如：C919_10002_D20200910"/>
          </el-form-item>
          <el-form-item label="上传文件：" required>
            <el-upload class="upload-demo" style="width:400px;height:200px;" drag :file-list="uploadFiles" :beforeUpload="beforeUpload" :http-request="componentImport">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">点击或将文件拖拽到这里上传，支持压缩包格式：.ZIP、.RAR，每次只支持一个压缩包上传，大小限制500M。</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="upload_list" v-show="active === 2" v-loading="uploadLoading" element-loading-text="数据导入中...">
      <FileTree :data="zipData" v-if="active === 2" :active="active" @change="dataChange" />
    </div>
    <div class="upload_success" v-show="active === 3">
      <div class="upload_success_message">
        <el-icon size="48" color="#67C23A"><CircleCheck /></el-icon>
        <div>
          本次成功导入数据 <span style="color: #02790e">{{ importNumber }}</span> 条，其中修改后导入的数据
          <span style="color: #f59a23">{{ updatedImportNumber }}</span> 条；未导入的数据 <span style="color: red">{{ notImportNumber }}</span> 条。
        </div>
      </div>
      <FileTree :data="importedData" v-if="active === 3" :active="active" />
    </div>
    <div class="option_btn">
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 1" @click="step('next')">下一步</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 2" @click="comfirmImport">确认导入</el-button>
      <el-button size="small" type="primary" :disabled="uploadLoading" v-show="active === 2" @click="step('pre')">上一步</el-button>
      <el-button size="small" type="primary" v-show="active === 3" @click="finish">完成</el-button>
      <el-button size="small" v-show="active !== 3" @click="cancel" :disabled="uploadLoading">取消</el-button>
    </div>
  </div>
</template>
<script  setup name="UploadElements">
import { preImport, getStructureTreeList, zipImport, cancelImport } from '@/api/elementsLibrary/index';
import FileTree from './FileTree.vue';

const emit = defineEmits(['handleEvent']);
const active = ref(1);
const uploadFiles = ref([]);
// 文件解析loading
const uploadLoading = ref(false);
// zip上传form表单
const uploadForm = ref({ structureModelId: '' ,indexFileName:''});
// 机型下拉列表
const structureModel = ref([]);
// zip包平铺数据
const zipData = ref([]);
// 导入后数据
const importedData = ref([]);
// 成功导入条数
const importNumber = ref(0);
// 修改后导入条数
const updatedImportNumber = ref(0);
//未导入条数
const notImportNumber = ref(0);
// 已修改的数据集合
const modifyDataIds = ref([]);
// 验证文件格式是否正确
const beforeUpload = (file) => {
  let isFile = file.name.split('.')[file.name.split('.').length - 1] == 'zip' || file.name.split('.')[file.name.split('.').length - 1] == 'rar';
  const isLt = file.size / 1024 / 1024 < 500;
  if (!isFile) {
    ElMessage.error('导入文件格式不正确');
    return false;
  }
  if (!isLt) {
    ElMessage.error(`导入文件太大，请交由系统管理员进行处理`);
    return false;
  }
  //清空filelist
  uploadFiles.value = [];
  return isFile;
};
// 读取压缩文件
const componentImport = async (file) => {
  uploadFiles.value.push(file.file);
};
const dataChange = (data) => {
  zipData.value = data.changeData;
  modifyDataIds.value = data?.modifyDataIds;
};
// 确认导入
const comfirmImport = () => {
  //调用导入接口
  uploadLoading.value = true;
  zipImport(zipData.value)
    .then((res) => {
      if (res) {
        importedData.value = res?.data?.partVoList;
        importNumber.value = res?.data?.importNumber;
        updatedImportNumber.value = res?.data?.updatedImportNumber;
        notImportNumber.value = res?.data?.notImportNumber;
        active.value++;
      }
      uploadLoading.value = false;
    })
    .catch(() => {
      uploadLoading.value = false;
      ElMessage({ showClose: true, message: '导入数据失败', type: 'error' });
    });
};
// zip文件解析
const uploadZipFile = () => {
  // 提交校验
  if (!uploadForm.value.structureModelId) {
    ElMessage({ showClose: true, message: '请选择机型！', type: 'error' });
    return;
  }
  if (uploadFiles.value.length === 0) {
    ElMessage({ showClose: true, message: '请上传文件！', type: 'error' });
    return;
  }
  const formData = new FormData();
  formData.append('file', uploadFiles.value[0]);
  formData.append('modelNumber', uploadForm.value.structureModelId);
  formData.append('indexFileName', uploadForm.value.indexFileName);
  uploadLoading.value = true;
  preImport(formData)
    .then((res) => {
      zipData.value = res?.data;
      if (res?.data.length === 0) {
        ElMessage({ showClose: true, message: '文件解析失败！', type: 'error' });
        return;
      }
      active.value++;
    })
    .finally(() => {
      uploadLoading.value = false;
    });
};
// 查询机型列表
const getStructureList = () => {
  getStructureTreeList({ parentId: 0 }).then((res) => {
    if (res) {
      structureModel.value = res.rows;
    }
  });
};
// 完成
const finish = () => {
  emit('handleEvent', { component: 'UploadElements', type: 'finish' });
};
// 上一步  下一步
const step = (type) => {
  if (type === 'next') {
    if (active.value === 1) {
      // 文件解析
      uploadZipFile();
    }
  } else {
    active.value--;
  }
};
//取消
const cancel = () => {
  if (modifyDataIds.value.length > 0) {
    // 调用取消接口
    cancelImport(modifyDataIds.value).then((res) => {
      console.log('cancel');
    });
  }
  emit('handleEvent', { component: 'UploadElements', type: 'cancel' });
};
onMounted(() => {
  getStructureList();
});
</script>
  <style lang="scss" scoped>
.upload_elements {
  padding: 10px;
  width: 100%;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: scroll;
  .steps {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top:30px;
  }
  .upload {
    width: 600px;
    margin-top: 20px;
    overflow-y: auto;
    overflow-x: hidden;
    // min-height: calc(100vh - 251px);
    .upload_content {
      width: 600px;
      // min-height: calc(100vh - 251px);
      // overflow: auto;
    }
  }
  .upload_list,
  .upload_success {
    margin-top: 10px;
    overflow: hidden;
    min-height: calc(100vh - 251px);
    width: 100%;
  }
  .option_btn {
    margin-top: 20px;
  }
  .upload_success {
    margin-top: 10px;
    .upload_success_message {
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  :deep(.el-step__title) {
    font-size: 12px;
  }
}
</style>